package com.ruoyi.system.controller;

import java.util.List;

import com.ruoyi.system.domain.Meet;
import com.ruoyi.system.domain.MeetUser;
import com.ruoyi.system.service.IMeetService;
import com.ruoyi.system.service.IMeetUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.MeetRequests;
import com.ruoyi.system.domain.vo.MeetRequestsVO;
import com.ruoyi.system.service.IMeetRequestsService;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.util.StringUtils;

/**
 * 会议申请管理Controller
 */
@RestController
@RequestMapping("/system/meetRequests")
public class MeetRequestsController extends BaseController {
    @Autowired
    private IMeetRequestsService meetRequestsService;

    @Autowired
    private IMeetUserService meetUserService;

    /**
     * 查询会议申请管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:meetRequests:list')")
    @GetMapping("/list")
    public TableDataInfo list(MeetRequests meetRequests) {
        startPage();
        List<MeetRequestsVO> list = meetRequestsService.selectMeetRequestsVOList(meetRequests);
        return getDataTable(list);
    }

    /**
     * 获取会议申请管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:meetRequests:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(meetRequestsService.selectMeetRequestsVOById(id));
    }

    /**
     * 修改会议申请管理
     */
    @PreAuthorize("@ss.hasPermi('system:meetRequests:edit')")
    @Log(title = "会议申请管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MeetRequests meetRequests) {
        // 参数校验
        if (meetRequests.getStatus() == null) {
            return error("状态不能为空");
        }
        
        // 驳回时需要填写原因
        if ("2".equals(meetRequests.getStatus()) && StringUtils.isEmpty(meetRequests.getContent())) {
            return error("驳回原因不能为空");
        }
        
        // 只有在审核通过时才创建会议用户关联
        if ("1".equals(meetRequests.getStatus())) {
            // 添加参数校验
            if (meetRequests.getMeetId() == null) {
                return error("会议ID不能为空");
            }
            if (meetRequests.getUserId() == null) {
                return error("用户ID不能为空");
            }
            
            MeetUser meetUser = new MeetUser();
            meetUser.setMeetId(meetRequests.getMeetId());
            meetUser.setUserId(meetRequests.getUserId());
            meetUser.setIsAttented("1");
            meetUserService.insertMeetUser(meetUser);
        }
        
        return toAjax(meetRequestsService.updateMeetRequests(meetRequests));
    }
}